/**
 * 可视化器选择和控制界面
 */
class VisualizerSelector {
    constructor(containerId = 'visualizer-controls') {
        this.container = document.getElementById(containerId);
        this.manager = null;
        this.currentVisualizer = null;
        this.controlsVisible = true;
        
        if (!this.container) {
            this.createContainer();
        }
        
        this.init();
    }

    createContainer() {
        this.container = document.createElement('div');
        this.container.id = 'visualizer-controls';
        this.container.className = 'visualizer-controls';
        document.body.appendChild(this.container);
    }

    init() {
        this.createControls();
        this.bindEvents();
        this.addStyles();
    }

    setManager(manager) {
        this.manager = manager;
        this.updateVisualizerList();
    }

    createControls() {
        this.container.innerHTML = `
            <div class="visualizer-panel">
                <div class="panel-header">
                    <h3>🎨 可视化效果</h3>
                    <button class="toggle-btn" id="toggleControls">−</button>
                </div>
                
                <div class="panel-content" id="panelContent">
                    <div class="visualizer-grid" id="visualizerGrid">
                        <!-- 可视化器选项将在这里生成 -->
                    </div>
                    
                    <div class="settings-section" id="settingsSection">
                        <h4>⚙️ 当前设置</h4>
                        <div class="settings-grid" id="settingsGrid">
                            <!-- 设置控件将在这里生成 -->
                        </div>
                    </div>
                    
                    <div class="preset-section">
                        <h4>🎯 预设方案</h4>
                        <div class="preset-buttons">
                            <button class="preset-btn" data-preset="calm">平静</button>
                            <button class="preset-btn" data-preset="energetic">活力</button>
                            <button class="preset-btn" data-preset="dreamy">梦幻</button>
                            <button class="preset-btn" data-preset="gaming">游戏</button>
                        </div>
                    </div>
                    
                    <div class="info-section" id="infoSection">
                        <h4>ℹ️ 当前效果信息</h4>
                        <div class="info-content" id="infoContent">
                            请选择一个可视化效果
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    updateVisualizerList() {
        if (!this.manager) return;

        const grid = document.getElementById('visualizerGrid');
        const visualizers = this.manager.getAvailableVisualizers();

        grid.innerHTML = visualizers.map(viz => `
            <div class="visualizer-card" data-id="${viz.id}">
                <div class="card-icon">${this.getVisualizerIcon(viz.category)}</div>
                <div class="card-title">${viz.name}</div>
                <div class="card-description">${viz.description}</div>
                <div class="card-category">${this.getCategoryName(viz.category)}</div>
            </div>
        `).join('');

        // 绑定选择事件
        grid.querySelectorAll('.visualizer-card').forEach(card => {
            card.addEventListener('click', () => {
                this.selectVisualizer(card.dataset.id);
            });
        });
    }

    getVisualizerIcon(category) {
        const icons = {
            'instrument': '🎹',
            'particle': '🌊',
            'physics': '⚽',
            'gaming': '⌨️',
            'wave': '〰️',
            '3d': '📦',
            'basic': '📊',
            'abstract': '🎨'
        };
        return icons[category] || '🎵';
    }

    getCategoryName(category) {
        const names = {
            'instrument': '乐器类',
            'particle': '粒子类',
            'physics': '物理类',
            'gaming': '游戏类',
            'wave': '波浪类',
            '3d': '立体类',
            'basic': '基础类',
            'abstract': '抽象类'
        };
        return names[category] || '其他';
    }

    selectVisualizer(id) {
        if (!this.manager) return;

        // 移除之前的选中状态
        document.querySelectorAll('.visualizer-card').forEach(card => {
            card.classList.remove('selected');
        });

        // 选中新的卡片
        const selectedCard = document.querySelector(`[data-id="${id}"]`);
        if (selectedCard) {
            selectedCard.classList.add('selected');
        }

        // 切换可视化器
        if (this.manager.switchTo(id)) {
            this.currentVisualizer = id;
            this.updateSettings();
            this.updateInfo(id);
        }
    }

    updateSettings() {
        if (!this.manager) return;

        const settingsGrid = document.getElementById('settingsGrid');
        const params = this.manager.getCurrentVisualizerParams();
        const currentSettings = this.manager.getCurrentSettings();

        settingsGrid.innerHTML = params.map(param => {
            return this.createSettingControl(param, currentSettings[param.key]);
        }).join('');

        // 绑定设置变更事件
        settingsGrid.querySelectorAll('input, select').forEach(input => {
            input.addEventListener('change', (e) => {
                this.updateSetting(e.target.dataset.key, e.target.value, e.target.type);
            });
        });
    }

    createSettingControl(param, currentValue) {
        const { key, label, type, min, max, step, options, default: defaultValue } = param;
        const value = currentValue !== undefined ? currentValue : defaultValue;

        switch (type) {
            case 'range':
                return `
                    <div class="setting-item">
                        <label>${label}</label>
                        <div class="range-container">
                            <input type="range" 
                                   data-key="${key}" 
                                   min="${min}" 
                                   max="${max}" 
                                   step="${step}" 
                                   value="${value}">
                            <span class="range-value">${value}</span>
                        </div>
                    </div>
                `;

            case 'color':
                return `
                    <div class="setting-item">
                        <label>${label}</label>
                        <input type="color" data-key="${key}" value="${value}">
                    </div>
                `;

            case 'boolean':
                return `
                    <div class="setting-item">
                        <label>${label}</label>
                        <input type="checkbox" data-key="${key}" ${value ? 'checked' : ''}>
                    </div>
                `;

            case 'select':
                const optionsHtml = options.map(opt => 
                    `<option value="${opt.value}" ${opt.value === value ? 'selected' : ''}>${opt.label}</option>`
                ).join('');
                return `
                    <div class="setting-item">
                        <label>${label}</label>
                        <select data-key="${key}">
                            ${optionsHtml}
                        </select>
                    </div>
                `;

            default:
                return `
                    <div class="setting-item">
                        <label>${label}</label>
                        <input type="text" data-key="${key}" value="${value}">
                    </div>
                `;
        }
    }

    updateSetting(key, value, type) {
        if (!this.manager) return;

        // 类型转换
        let convertedValue = value;
        if (type === 'range' || type === 'number') {
            convertedValue = parseFloat(value);
        } else if (type === 'checkbox') {
            convertedValue = document.querySelector(`[data-key="${key}"]`).checked;
        }

        // 更新设置
        this.manager.updateSettings({ [key]: convertedValue });

        // 更新显示值（对于range类型）
        if (type === 'range') {
            const rangeValue = document.querySelector(`[data-key="${key}"]`).parentNode.querySelector('.range-value');
            if (rangeValue) {
                rangeValue.textContent = convertedValue;
            }
        }
    }

    updateInfo(visualizerId) {
        const infoContent = document.getElementById('infoContent');
        const visualizers = this.manager.getAvailableVisualizers();
        const viz = visualizers.find(v => v.id === visualizerId);

        if (viz) {
            infoContent.innerHTML = `
                <div class="info-row"><strong>名称:</strong> ${viz.name}</div>
                <div class="info-row"><strong>描述:</strong> ${viz.description}</div>
                <div class="info-row"><strong>类别:</strong> ${this.getCategoryName(viz.category)}</div>
                <div class="info-row"><strong>作者:</strong> ${viz.author}</div>
                <div class="info-row"><strong>版本:</strong> ${viz.version}</div>
            `;
        }
    }

    bindEvents() {
        // 切换控制面板显示/隐藏
        document.getElementById('toggleControls').addEventListener('click', () => {
            this.toggleControls();
        });

        // 预设方案
        document.querySelectorAll('.preset-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                this.applyPreset(btn.dataset.preset);
            });
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.altKey) {
                switch (e.key) {
                    case 'v':
                        e.preventDefault();
                        this.toggleControls();
                        break;
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8':
                    case '9':
                        e.preventDefault();
                        const index = parseInt(e.key) - 1;
                        const visualizers = this.manager?.getAvailableVisualizers();
                        if (visualizers && visualizers[index]) {
                            this.selectVisualizer(visualizers[index].id);
                        }
                        break;
                }
            }
        });
    }

    toggleControls() {
        const content = document.getElementById('panelContent');
        const toggleBtn = document.getElementById('toggleControls');
        
        this.controlsVisible = !this.controlsVisible;
        
        if (this.controlsVisible) {
            content.style.display = 'block';
            toggleBtn.textContent = '−';
        } else {
            content.style.display = 'none';
            toggleBtn.textContent = '+';
        }
    }

    applyPreset(presetName) {
        const presets = {
            calm: {
                sensitivity: 0.8,
                primaryColor: '#4CAF50',
                secondaryColor: '#81C784'
            },
            energetic: {
                sensitivity: 1.5,
                primaryColor: '#FF5722',
                secondaryColor: '#FF8A65'
            },
            dreamy: {
                sensitivity: 1.0,
                primaryColor: '#9C27B0',
                secondaryColor: '#BA68C8'
            },
            gaming: {
                sensitivity: 1.2,
                primaryColor: '#00FF00',
                secondaryColor: '#00FFFF'
            }
        };

        const preset = presets[presetName];
        if (preset && this.manager) {
            this.manager.updateSettings(preset);
            this.updateSettings(); // 刷新设置显示
        }
    }

    addStyles() {
        if (document.getElementById('visualizer-selector-styles')) return;

        const styles = document.createElement('style');
        styles.id = 'visualizer-selector-styles';
        styles.textContent = `
            .visualizer-controls {
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 1000;
                max-width: 350px;
                font-family: Arial, sans-serif;
            }

            .visualizer-panel {
                background: rgba(0, 0, 0, 0.9);
                border-radius: 15px;
                padding: 0;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
                backdrop-filter: blur(10px);
                border: 1px solid rgba(255, 255, 255, 0.1);
                color: white;
            }

            .panel-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 15px 20px;
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            }

            .panel-header h3 {
                margin: 0;
                font-size: 1.2rem;
            }

            .toggle-btn {
                background: none;
                border: none;
                color: white;
                font-size: 1.5rem;
                cursor: pointer;
                padding: 0;
                width: 30px;
                height: 30px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .toggle-btn:hover {
                background: rgba(255, 255, 255, 0.1);
            }

            .panel-content {
                padding: 20px;
                max-height: 70vh;
                overflow-y: auto;
            }

            .visualizer-grid {
                display: grid;
                gap: 10px;
                margin-bottom: 20px;
            }

            .visualizer-card {
                background: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                padding: 15px;
                cursor: pointer;
                transition: all 0.3s ease;
                border: 2px solid transparent;
            }

            .visualizer-card:hover {
                background: rgba(255, 255, 255, 0.2);
                transform: translateY(-2px);
            }

            .visualizer-card.selected {
                border-color: #4CAF50;
                background: rgba(76, 175, 80, 0.2);
            }

            .card-icon {
                font-size: 2rem;
                text-align: center;
                margin-bottom: 8px;
            }

            .card-title {
                font-weight: bold;
                margin-bottom: 5px;
                text-align: center;
            }

            .card-description {
                font-size: 0.9rem;
                opacity: 0.8;
                text-align: center;
                margin-bottom: 5px;
            }

            .card-category {
                font-size: 0.8rem;
                text-align: center;
                opacity: 0.6;
                background: rgba(255, 255, 255, 0.1);
                padding: 2px 8px;
                border-radius: 12px;
                display: inline-block;
                width: 100%;
                text-align: center;
            }

            .settings-section, .preset-section, .info-section {
                margin-bottom: 20px;
                padding: 15px;
                background: rgba(255, 255, 255, 0.05);
                border-radius: 10px;
            }

            .settings-section h4, .preset-section h4, .info-section h4 {
                margin: 0 0 15px 0;
                font-size: 1rem;
            }

            .settings-grid {
                display: grid;
                gap: 15px;
            }

            .setting-item {
                display: flex;
                flex-direction: column;
                gap: 5px;
            }

            .setting-item label {
                font-size: 0.9rem;
                opacity: 0.9;
            }

            .range-container {
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .range-container input[type="range"] {
                flex: 1;
            }

            .range-value {
                font-size: 0.9rem;
                min-width: 40px;
                text-align: right;
            }

            .setting-item input, .setting-item select {
                background: rgba(255, 255, 255, 0.1);
                border: 1px solid rgba(255, 255, 255, 0.2);
                border-radius: 5px;
                padding: 8px;
                color: white;
                font-size: 0.9rem;
            }

            .setting-item input[type="checkbox"] {
                width: 20px;
                height: 20px;
                accent-color: #4CAF50;
            }

            .preset-buttons {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 10px;
            }

            .preset-btn {
                background: linear-gradient(45deg, #667eea, #764ba2);
                border: none;
                color: white;
                padding: 10px;
                border-radius: 8px;
                cursor: pointer;
                font-size: 0.9rem;
                transition: transform 0.2s;
            }

            .preset-btn:hover {
                transform: translateY(-2px);
            }

            .info-content {
                font-size: 0.9rem;
            }

            .info-row {
                margin-bottom: 8px;
                padding: 5px 0;
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            }

            .info-row:last-child {
                border-bottom: none;
            }

            /* 滚动条样式 */
            .panel-content::-webkit-scrollbar {
                width: 8px;
            }

            .panel-content::-webkit-scrollbar-track {
                background: rgba(255, 255, 255, 0.1);
                border-radius: 4px;
            }

            .panel-content::-webkit-scrollbar-thumb {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 4px;
            }

            .panel-content::-webkit-scrollbar-thumb:hover {
                background: rgba(255, 255, 255, 0.5);
            }

            /* 响应式设计 */
            @media (max-width: 768px) {
                .visualizer-controls {
                    position: fixed;
                    top: 10px;
                    right: 10px;
                    left: 10px;
                    max-width: none;
                }
                
                .preset-buttons {
                    grid-template-columns: 1fr;
                }
            }
        `;

        document.head.appendChild(styles);
    }

    // 公共API方法
    show() {
        this.container.style.display = 'block';
    }

    hide() {
        this.container.style.display = 'none';
    }

    getCurrentVisualizer() {
        return this.currentVisualizer;
    }

    // 导出/导入设置
    exportSettings() {
        if (!this.manager) return null;
        
        return {
            visualizer: this.currentVisualizer,
            settings: this.manager.getCurrentSettings()
        };
    }

    importSettings(config) {
        if (!this.manager || !config) return false;
        
        if (config.visualizer) {
            this.selectVisualizer(config.visualizer);
        }
        
        if (config.settings) {
            this.manager.updateSettings(config.settings);
            this.updateSettings();
        }
        
        return true;
    }
}

// 导出到全局
window.VisualizerSelector = VisualizerSelector;
